home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: presby.edu!jtbell
- From: jtbell@presby.edu (Jon Bell)
- Subject: Re: const member functions..
- Message-ID: <DpvCqC.2As@presby.edu>
- Date: Sun, 14 Apr 1996 20:25:24 GMT
- References: <4krjlj$spn@canopus.cc.umanitoba.ca>
- Organization: Presbyterian College, Clinton, South Carolina USA
-
- <rdanse@pobox.com> wrote:
- >What does the const operator do when used at the end of a member
- >function declaration in an object class?
-
- It signals to the compiler that that member function is guaranteed not to
- change the member data of the object that it is a member of.
-
- If you try to write a const member function that *does* change member
- data, the compiler calls it an error.
-
- If you declare an object as const, you may use only the const member
- functions of that object. If you try to use a non-const member function
- of a const object, the compiler calls it an error.
-
- Example:
-
- class Vector
- {
- Vector(double X, double Y, double Z) // constructor
- { X_ = X; Y_ = Y; Z_ = Z };
- double Length (void) const // calculates the length of a vector
- { return sqrt (X_*X_ + Y_*Y_ + Z_*Z); };
- void SetVector (double X, double Y, double Z) // sets the components
- { X_ = X; Y_ = Y; Z_ = Z }; // of a vector
- ... etc...
- private
- double X_, Y_, Z_;
- };
-
-
- int main (void)
- {
- const Vector
- g (0, 0, -9.8); // downward acceleration of gravity, which is a
- // constant for most purposes on Earth's surface
-
- cout << g.Length(); // OK because Length is const
-
- g.SetVector(0, 0, -1.6); // not OK because SetVector is not const
-
- ... etc...
- }
-
-
- --
- Jon Bell <jtbell@presby.edu> Presbyterian College
- Dept. of Physics and Computer Science Clinton, South Carolina USA
-